//
//  WriteDDViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-3-7.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "WriteDDViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MainTabBarController.h"
#import "ApplyDDViewController.h"
@interface WriteDDViewController ()

@end

@implementation WriteDDViewController
@synthesize m_ProdIDs;
@synthesize m_ProdNums;
@synthesize m_ProPrice;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
        _IsRequested =NO;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        _SendWayType = 0;
        _NoneImg= [[UIImage imageNamed:@"select.png"] retain];
        _SelectImg = [[UIImage imageNamed:@"checked.png"] retain];
    }
    return self;
}

-(void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_SelectImg release];
    [_NoneImg release];
    [_NameField release];
    [_PhoneField release];
    [_AddressField release];
    [_YDDDic release];
    [_NavBtt release];
    [_DDTableView release];
    [m_ProdIDs release];
    [m_ProdNums release];
    [m_ProPrice release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"购物车"];
    
    m_titleBttBarItem = [[MainTabBarController setTitle:@"购物车"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    

    _DDTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44) style:UITableViewStyleGrouped];
    _DDTableView.delegate = self;
    _DDTableView.dataSource = self;
    [_DDTableView setBackgroundView:nil];
    [_DDTableView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_DDTableView];
    
    UIView* tBottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    [tBottomView setBackgroundColor:[UIColor clearColor]];
    UIButton* tApplyBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    tApplyBtt.frame =CGRectMake(10, 5, 300, 40);
    [tApplyBtt setImage:[UIImage imageNamed:@"button_yellow_l.png"] forState:UIControlStateNormal];
    [tBottomView addSubview:tApplyBtt];
    [tApplyBtt addTarget:self action:@selector(cofirmDD) forControlEvents:UIControlEventTouchUpInside];
    UILabel* tBttlab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 300, 20)];
    [tBttlab setBackgroundColor:[UIColor clearColor]];
    [tBttlab setTextColor:[UIColor whiteColor]];
    [tBttlab setText:@"提交订单"];
    tBttlab.textAlignment =UITextAlignmentCenter;
    [tBttlab setFont:[UIFont boldSystemFontOfSize:17]];
    [tApplyBtt addSubview:tBttlab];
    [tBttlab release];
    _DDTableView.tableFooterView = tBottomView;
    [tBottomView release];
    
    
    _NameField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    _PhoneField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    _AddressField = [[UITextField alloc] initWithFrame:CGRectMake(64, 10, 220, 20)];
    
    _NameField.delegate = self;
    _PhoneField.delegate = self;
    _AddressField.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
     [self.navigationController.navigationBar addSubview:m_titleBttBarItem];
    if (!_IsRequested) {
        [self requestDetailData];
    }
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
    [m_titleBttBarItem removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}

//提交订单
-(void) cofirmDD
{
    ApplyDDViewController* tApplyVC = [[ApplyDDViewController alloc] init];
    tApplyVC.navigationItem.hidesBackButton =YES;
    tApplyVC.m_Address = _AddressField.text;
    tApplyVC.m_Name= _NameField.text;
    tApplyVC.m_Phone= _PhoneField.text;
    tApplyVC.m_ProdIDs= m_ProdIDs;
    tApplyVC.m_ProdNums= m_ProdNums;
    tApplyVC.m_ProPrice= m_ProPrice;
    NSArray*  tKDArr = [_YDDDic objectForKey:@"shipping"];
    NSDictionary* tKDDic = [tKDArr objectAtIndex:_SendWayType];
    tApplyVC.m_Shipping= [tKDDic objectForKey:@"shipping_id"];
    [self.navigationController pushViewController:tApplyVC  animated:YES];
    [tApplyVC release];
}

-(void) requestAddChartFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            [_YDDDic release];
            _YDDDic =nil;
            _YDDDic = [tDataDic objectForKey:@"data"];
            [_YDDDic retain];
            
            _NameField.text = [_YDDDic objectForKey:@"name"];
            _PhoneField.text = [_YDDDic objectForKey:@"mobile"];
            _AddressField.text = [_YDDDic objectForKey:@"address"];
            
            [_DDTableView reloadData];
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    _IsRequested = YES;
    [self hudWasHidden:nil];
}

-(void) requestDetailData
{
    
    MainTabBarController* tMainTabController = (MainTabBarController*)self.navigationController.tabBarController;
    
    [self addHudLoad];
    NSDictionary* tDataDic = [tMainTabController.m_UserDic objectForKey:@"data"];
    NSString* tURLStr = @"";
    
    if ( tMainTabController.m_UserDic != nil) {
        tURLStr = [NSString stringWithFormat:@"%@ac=checkOrder&product_ids=%@&product_numbers=%@&price=%@&cur_user_id=%@",RequestCurrentURL,m_ProdIDs,m_ProdNums,m_ProPrice,[tDataDic objectForKey:@"user_id"]];
    }else{
        tURLStr = [NSString stringWithFormat:@"%@ac=checkOrder&product_ids=%@&product_numbers=%@&price=%@",RequestCurrentURL,m_ProdIDs,m_ProdNums,m_ProPrice];
    }
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestAddChartFinish:)];
    [tRequestPage startAsynchronous];

    
}

-(void) requestDetailFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}


#pragma mark-
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) {
        _SendWayType = indexPath.row;
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

#pragma mark-
#pragma mark UITableViewDataSource
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"配送地址";
    }
    return @"选择配送方式";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }else{
        return [[_YDDDic objectForKey:@"shipping"] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* tNameCell  =@"norcell";
    int tRow = indexPath.row;
    int tSection = indexPath.section;
    
    UITableViewCell* tCell = [tableView dequeueReusableCellWithIdentifier:tNameCell];
    if (tCell == nil) {
        tCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tNameCell] autorelease];
        UILabel* tTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(62, 10, 240,20)];
        [tTitleLab setBackgroundColor:[UIColor clearColor]];
        [tTitleLab setFont:[UIFont systemFontOfSize:15]];
        tTitleLab.tag =50;
        [tCell addSubview:tTitleLab];
        [tTitleLab release];
        
        UILabel* tPriceLab = [[UILabel alloc] initWithFrame:CGRectMake(250, 10, 50,20)];
        [tPriceLab setBackgroundColor:[UIColor clearColor]];
        [tPriceLab setFont:[UIFont systemFontOfSize:15]];
        tPriceLab.tag =51;
        tPriceLab.textAlignment= UITextAlignmentRight;
        [tCell addSubview:tPriceLab];
        [tPriceLab release];
        
        UIImageView* tSelectImg = [[UIImageView alloc] initWithFrame:CGRectMake(20, 12, 20, 20)];
        tSelectImg.tag =52;
        [tCell addSubview:tSelectImg];
        [tSelectImg release];
    }
    for (id tSubObject in tCell.subviews) {
        if ([tSubObject isKindOfClass:[UITextField class]]) {
            [tSubObject removeFromSuperview];
        }
    }
    UILabel* tTitleLab = (UILabel*)[tCell viewWithTag:50];
    UILabel* tPriceLab = (UILabel*)[tCell viewWithTag:51];
    UIImageView* tImgView = (UIImageView*)[tCell viewWithTag:52];
    tPriceLab.text =@"";
    [tImgView setImage:nil];
    if (tSection == 0) {
        tCell.selectionStyle = UITableViewCellSelectionStyleNone;
        tTitleLab.frame =CGRectMake(18, 10, 240,20);
        if (tRow == 0) {
             tTitleLab.text =@"姓名";
            [tCell addSubview:_NameField];
        }else if (tRow == 1) {
            tTitleLab.text =@"手机";
            [tCell addSubview:_PhoneField];
        }else if (tRow == 2) {
            tTitleLab.text =@"地址";
            [tCell addSubview:_AddressField];
        }
        
    }else if(tSection == 1){
        tCell.selectionStyle = UITableViewCellSelectionStyleBlue;
        tTitleLab.frame =CGRectMake(52, 10, 240,20);
        NSArray*  tKDArr = [_YDDDic objectForKey:@"shipping"];
        NSDictionary* tKDDic = [tKDArr objectAtIndex:tRow];
        tTitleLab.text =[tKDDic objectForKey:@"name"];
        
        tPriceLab.text =[NSString stringWithFormat:@"¥ %d",[[tKDDic objectForKey:@"price"] intValue]];
        
        if (_SendWayType == tRow) {
            [tImgView setImage:_SelectImg];
        }else{
            [tImgView setImage:_NoneImg];
        }
    }
    return tCell;
}


#pragma mark keyboard notifications

- (void)keyboardWillShow:(NSNotification *)notification
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
		NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
		NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
		CGRect keyboardBounds;
		[keyboardBoundsValue getValue:&keyboardBounds];
		//UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(keyboardOver)];
        _DDTableView.frame =CGRectMake(0, 0, 320, self.view.frame.size.height-44-keyboardBounds.size.height);
        [UIView commitAnimations];
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
	}
#endif
}

-(void)keyboardWillHide:(NSNotification *)notification
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
		NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
		NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
		CGRect keyboardBounds;
		[keyboardBoundsValue getValue:&keyboardBounds];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        _DDTableView.frame =CGRectMake(0, 0, 320, self.view.frame.size.height-44);
        [UIView commitAnimations];
        
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
	}
#endif
}


#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}





@end
